package cn.thread.pool.dynamic.thread.pool.sdk.register.redis;

import cn.thread.pool.dynamic.thread.pool.sdk.domain.model.entity.ThreadPoolConfigEntity;
import cn.thread.pool.dynamic.thread.pool.sdk.domain.model.valobj.RegistryEnumVO;
import cn.thread.pool.dynamic.thread.pool.sdk.register.Iregister;
import org.redisson.api.RBucket;
import org.redisson.api.RMap;
import org.redisson.api.RedissonClient;

import java.time.Duration;
import java.util.List;

/**
 * @author: xiaoxie
 * create: 2025-02-11 21:13
 * @BelongsProject: custom-dynamic-thread-pool
 * @BelongsPackage: cn.thread.pool.dynamic.thread.pool.sdk.register.redis
 * description: redis注册中心
 */
public class redisRegister implements Iregister {
    private final RedissonClient redissonClient;

    public redisRegister(RedissonClient redissonClient) {
        this.redissonClient = redissonClient;
    }

    @Override
    public void registerThreadPoolList(List<ThreadPoolConfigEntity> threadPoolConfigEntityList) {
        // 采用 Hash 存储，避免重复
        RMap<String, ThreadPoolConfigEntity> map = redissonClient.getMap(RegistryEnumVO.THREAD_POOL_CONFIG_LIST_KEY.getKey());
        for (ThreadPoolConfigEntity threadPoolConfigEntity : threadPoolConfigEntityList) {
            String threadPoolName = threadPoolConfigEntity.getThreadPoolName();
            // 直接调用 put 即可覆盖已有值
            map.put(threadPoolName, threadPoolConfigEntity);
        }
    }

    @Override
    public void registerThreadPoolConfigParameter(ThreadPoolConfigEntity threadPoolConfigEntity) {
        RBucket<ThreadPoolConfigEntity> bucket = redissonClient.getBucket(RegistryEnumVO.THREAD_POOL_CONFIG_PARAMETER_LIST_KEY.getKey()
                + "_" + threadPoolConfigEntity.getAppName() + "_" + threadPoolConfigEntity
                .getThreadPoolName());
        bucket.set(threadPoolConfigEntity, Duration.ofDays(30));

    }
}
